package myschool.filter;

import myschool.util.StrUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @author oldliu
 * @since 1.0
 */

 @WebFilter(value = "/*",initParams = {@WebInitParam(name = "encoding",value = "utf-8")})
public class TimeFilter implements Filter {
    public TimeFilter(){

    }
    private String enc;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("TimeFilter初始化了");
        //初始化参数
        this.enc=filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了：TimeFilter");
        try {
            System.out.println("设置了字符集:" + this.enc);
            long start = System.nanoTime();
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            request.setCharacterEncoding(this.enc);
            String path = request.getServletPath();//请求路径
            System.out.println("您访问了：" + path + ",时间是" + new Date());
            String ip = request.getRemoteHost();
            //限制ip访问
            if (ip.contains("192.168.100.85")) {
                request.getRequestDispatcher("/error.jsp").forward(request, servletResponse);
                return;
            }
            //放行！！！
            filterChain.doFilter(request, servletResponse);
            long end = System.nanoTime();
            System.out.println(path + "耗时 " + (end - start) + "纳秒");
        }finally {
            System.out.println("退出了：TimeFilter");
        }

    }

    @Override
    public void destroy() {
        System.out.println("TimeFilter销毁了");
    }
}
